<script setup>
import request from '@/utils/request.js'
import { ref, computed, onMounted, watch } from 'vue';
import { useUserStore, usePartnerStore } from '@/stores/index.js'
import { ElContainer, ElAside, ElMain, ElMenu, ElMenuItem, ElCard, ElButton, ElTimeline, ElTimelineItem, ElMessage, ElLoading ,ElMessageBox} from 'element-plus';
const newMessage = ref('');
const userStore = useUserStore();
const partnerStore = usePartnerStore();

// 默认头像
const DEFAULT_AVATAR = 'https://placehold.co/50x50/cccccc/ffffff?text=头像';

// 伙伴列表和聊天记录（初始化为空对象）
const chatRecords = ref({});


const currentPartner = computed(() => {
  const key = String(partnerStore.activePartnerKey);
  return partnerStore.partners.find(p => p.id === key) || {
    avatar: DEFAULT_AVATAR,
    nickname: '未知用户',
    major: '',
    intro: ''
  };
});

// 当前伙伴的聊天记录（逻辑不变）
const currentChatRecords = computed(() => {
  return chatRecords.value[partnerStore.activePartnerKey] || [];
});

// 切换伙伴：
const handlePartnerSelect = async(key) => {
  partnerStore.setActivePartner(key); // 先更新 Pinia 状态
  console.log(partnerStore.partners);
  await getChatMessages(key); // 再加载聊天记录
};

// 取聊天记录
const getChatMessages = async (partnerId) => {
  try {
    const res = await request.get('/getChatMessages', {
      params: {
        userId: userStore.userId,
        partnerId: partnerId
      }
    });
    chatRecords.value[partnerId] = res.data.chatList || []
    newMessage.value = '';
  } catch (error) {
    console.error('获取聊天记录失败:', error);
    if(error.response && error.response.status === 403){
      ElMessage({ type: 'info', message: '暂无聊天记录' });
    }
    ElMessage({ type: 'error', message: '聊天记录加载失败' });
    chatRecords.value[partnerId] = [];
  }
};
//获取伙伴信息
const getPartnerInfo = async () => {
  await partnerStore.fetchPartners(userStore.userId);
  if (partnerStore.activePartnerKey) {
    await getChatMessages(partnerStore.activePartnerKey);
  }
};

// 6. 发送消息
const sendMessage = async () => {
  const messageContent = newMessage.value.trim();
  if (!messageContent) return;

  const now = new Date();
  const timeStr = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
  const currentPartnerId = partnerStore.activePartnerKey; // 用 Pinia 的选中ID
  const currentUserId = userStore.userId;

  if (!chatRecords.value[currentPartnerId]) {
    chatRecords.value[currentPartnerId] = [];
  }
  const tempMessage = {
    content: messageContent,
    time: timeStr,
    isMe: true,
    isRead: 1
  };
  chatRecords.value[currentPartnerId].push(tempMessage);
  newMessage.value = '';

  try {
    await request.post('/sendChatMessage', {
      senderId: currentUserId,
      receiverId: currentPartnerId,
      content: messageContent,
      type: 1
    });
    await getChatMessages(partnerStore.activePartnerKey);
  } catch (error) {
    chatRecords.value[currentPartnerId].pop();
    ElMessage({ type: 'error', message: '消息发送失败，请重试' });
    console.error('发送消息接口异常:', error);
  }
};
//撤回消息
const chatWithdraw =async(messageId,senderId)=>{
  // 是否确认撤回
  ElMessageBox.confirm('确定要撤回这条消息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
      try{
      const res = await request.post('/chatWithdraw',{
      sender_id:senderId,
      id:messageId
    })
    if(res.status=200){
        ElMessage({ type: 'success', message: '消息撤回成功' });
    }
     await getChatMessages(partnerStore.activePartnerKey);
    }catch(error){
      const errMsg = error.response?.data?.message || '消息撤回失败，请重试';
      // 显示后端返回的真实提示（比如“消息发送超过2分钟，无法撤回”）
      ElMessage({ type: 'error', message: errMsg });
      // 优化控制台日志：明确是业务提示，不是代码异常
      console.log('撤回操作提示:', errMsg);
    }
  }).catch(() => {

  });

  }
const chatReport =()=>{
  console.log("举报操作");
}
watch(
  () => partnerStore.activePartnerKey,
  async (newPartnerId) => {
    if (newPartnerId) {
      await getChatMessages(newPartnerId);
    }
  },
  { immediate: false }
);
// 页面挂载初始化（逻辑不变）
onMounted(() => {
  getPartnerInfo();
});
</script>
<template>
  <div class="app-container">
    <el-container class="main-container">
      <el-aside width="320px" class="partner-aside">
        <div class="menu-header">
          <h3 class="menu-title">伙伴列表</h3>
        </div>

        <el-menu
          :default-active="partnerStore.activePartnerKey"
          class="partner-menu"
          @select="handlePartnerSelect"
          background-color="transparent"
        >
          <!-- 加载中状态：匹配 .empty 样式，居中显示 -->
          <div v-if="partnerStore.isLoading" class="empty">加载伙伴中...</div>

          <!-- 无伙伴状态：同上，仅在无数据时显示 -->
          <div v-else-if="partnerStore.partners.length === 0" class="empty">暂无伙伴</div>

          <!-- 伙伴菜单项：严格匹配 .partner-menu-item 层级（img + .partner-info） -->
          <el-menu-item
            v-for="item in partnerStore.partners"
            :key="item.id"
            :index="item.id"
            class="partner-menu-item"
          >
            <!-- 头像：匹配 .partner-avatar 样式（宽高60px、边框、间距） -->
            <img :src="item.avatar || DEFAULT_AVATAR" class="partner-avatar" />

            <!-- 信息区：匹配 .partner-info 样式（flex-column、flex:1） -->
            <div class="partner-info">
              <!-- 昵称+专业：匹配 .partner-name 样式（字体16px、截断） -->
              <span class="partner-name">{{ item.nickname }}|{{ item.major || '未填专业' }}</span>
              <!-- 描述：改<p>标签！匹配 .partner-desc 样式（margin:0、字体12px） -->
              <p class="partner-desc">{{ item.intro || '暂无简介' }}</p>
            </div>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 右侧内容区：匹配 .content-main 样式（flex-column、padding） -->
      <el-main class="content-main">
        <!-- 聊天头部：匹配 .chat-header 样式（margin-bottom:20px） -->
        <el-card class="chat-header" shadow="never" border-radius="8px">
          <div class="chat-header-content">
            <!-- 头部头像：匹配 .chat-header-avatar 样式（宽高60px、间距20px） -->
            <img :src="currentPartner.avatar || DEFAULT_AVATAR" class="chat-header-avatar" />

            <!-- 头部信息：匹配 .chat-header-info 样式（flex-column） -->
            <div class="chat-header-info">
              <h3 class="chat-header-name">{{ currentPartner.nickname }}|{{ currentPartner.major || '未填专业' }}</h3>
              <p class="chat-header-desc">{{ currentPartner.intro || '暂无简介' }}</p>
            </div>
          </div>
        </el-card>

        <!-- 聊天记录卡片：匹配 .chat-records-card 样式（flex:1、height:0） -->
        <el-card class="chat-records-card" shadow="never" border-radius="8px">
          <!-- 记录容器：匹配 .chat-records-container 样式（height:100%） -->
          <div class="chat-records-container">
            <!-- 无聊天记录提示：匹配 .chat-empty 样式（居中、padding40px） -->
            <div v-if="currentChatRecords.length === 0 && !partnerStore.isLoading" class="chat-empty">
              暂无聊天记录，开始对话吧～
            </div>

            <!-- 聊天时间线：有记录时显示，匹配 .timeline-item-me/.other 样式 -->
            <el-timeline v-else  >
              <el-timeline-item
                v-for="(record, idx) in currentChatRecords"
                :key="idx"
                :timestamp="record.time"
                :class="record.isMe ? 'timeline-item-me' : 'timeline-item-other'"
                line-type="dashed"
              >
                <!-- 消息项：匹配 .chat-record-item 样式（max-width:80%、break-word） -->
                <!-- 自己的消息（isMe 为 true 时显示） -->
              <div
                class="chat-record-item chat-record-me"
                v-if="record.isMe"
              >
                <div class="chat-record-content" @click="chatWithdraw(record.messageId,record.senderId)">
                  {{ record.content }}
                </div>
              </div>

              <!-- 他人的消息（isMe 为 false 时显示） -->
              <div
                class="chat-record-item chat-record-other"
                v-else
              >
                <div class="chat-record-content" @click="chatReport()">
                  {{ record.content }}
                </div>
              </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>

        <!-- 输入区域：匹配 .chat-input-card 样式（margin-top:auto 固定底部） -->
        <el-card class="chat-input-card" shadow="never" border-radius="8px">
          <!-- 输入容器：匹配 .chat-input-container 样式（flex-column） -->
          <div class="chat-input-container">
            <!-- 输入框：匹配 .chat-input 样式（margin-bottom:10px） -->
            <el-input
              v-model="newMessage"
              @keyup.enter="sendMessage"
              type="textarea"
              :rows="3"
              placeholder="输入消息..."
              resize="none"
              class="chat-input"
              border-radius="8px"
            />

            <!-- 发送按钮：匹配 .send-button 样式（align-self:flex-end） -->
            <el-button
              type="primary"
              class="send-button"
              @click="sendMessage"
              :disabled="!newMessage.trim()"
              size="default"
              border-radius="8px"
            >
              发送
            </el-button>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>


<style scoped>
.app-container {
  height: 100vh;
  background-color: #e6f7ef;
}

.main-container {
  height: calc(100vh - 20px);
}

/* 左侧边栏优化 */
.partner-aside {
  background-color: #fff;
  border-right: 1px solid #ebeef5;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.menu-header {
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
}

.menu-title {
  font-size: 16px;
  color: #303133;
  font-weight: 600;
  margin: 0;
}

/* 菜单整体样式 */
.partner-menu {
  border-right: none;
  flex: 1;
  overflow-y: auto;
}

/* 菜单项样式 */
.partner-menu-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  height: 100px;
  margin: 8px 0;
  border-radius: 8px;
  transition: all 0.3s;
}

.partner-menu-item:hover {
  background-color: #f0f9f4;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 头像样式 */
.partner-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 15px;
  border: 2px solid #e6f7ef;
}

/* 信息区域样式 */
.partner-info {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 0;
  justify-content: center;
  height: 100%;
}

.partner-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  margin-bottom: 6px;
  line-height: 1.2;
}

.partner-desc {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  margin: 0;
  line-height: 1.2;
}

.content-main {
  padding: 0 20px 20px 20px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 聊天头部样式 */
.chat-header {
  margin-bottom: 20px;
}

.chat-header-content {
  display: flex;
  align-items: center;
}

.chat-header-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 20px;
}

.chat-header-info {
  display: flex;
  flex-direction: column;
}

.chat-header-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 5px;
}

.chat-header-desc {
  font-size: 14px;
  color: #909399;
}

/* 聊天记录卡片 */
.chat-records-card {
  flex: 1;
  margin-bottom: 20px;
  height: 0; /* 关键：允许flex子项收缩 */
  overflow-y: auto;
}

.chat-records-container {
  height: 100%;

}

/* 消息项样式 */
.chat-record-item {
  max-width: 80%;
  word-break: break-word;
}

.chat-record-me {
  margin-left: auto;
  text-align: right;
}

.chat-record-other {
  margin-right: auto;
  text-align: left;
}

.chat-record-content {
  padding: 10px 15px;
  border-radius: 4px;
  line-height: 1.5;
  /* 宽度自适应 */
  display: inline-block;
  max-width: 100%;
  word-wrap: break-word;
}

.chat-record-me .chat-record-content {
  background-color: #165dff;
  color: white;
  border-radius: 18px 18px 0 18px;
  cursor: pointer;
}

.chat-record-other .chat-record-content {
  background-color: #f0f0f0;
  color: #333;
  border-radius: 18px 18px 18px 0;
  cursor: pointer;
}

.timeline-item-me .el-timeline-item__timestamp {
  text-align: right;
  padding-right: 20px;
}

.timeline-item-other .el-timeline-item__timestamp {
  text-align: left;
  padding-left: 20px;
}

/* 输入区域样式 */
.chat-input-card {
  margin-top: auto; /* 固定在底部 */
}

.chat-input-container {
  display: flex;
  flex-direction: column;
}

.chat-input {
  margin-bottom: 10px;
}

.send-button {
  align-self: flex-end;
}
</style>
